<template>
  <view class="page-container bg-ff">
    <view class="flex items-center justify-center py-24">
      <view class="lh-44 font-30 text-60 flex items-center pb-2">
        <u-icon name="clock" color="#606266" size="18"></u-icon><view class="ml-6">倒计时：</view>
      </view>
      <u-count-down :time="time" format="HH:mm:ss" @change="onCountDownChange"></u-count-down></view>
    <view class="border-b-1 border-dd relative top10"></view>
    <swiper class="page-body" :current="currentIndex" @change="onSwiperChange">
      <swiper-item v-for="(item, index) in list" :key="index">
        <view v-if="index<=currentIndex+2 && index>=currentIndex-2">
          <view class="py-32 px-24 font-32 lh-48">
            <text>{{index+1}}、</text>
            <image :src="questionType[item.subjectType]" class="w-72 h-34 relative top-6 right-4" />{{ item.content }}
          </view>
          <view v-for="(value, label, index) in item.options" :key="index" @click="onRadioChange(label)">
            <view class="py-32 px-24 bg-ff flex items-center" :class="{'bg-f7':index%2 ===0}" >
              <view class="border border-dd icon-40 rounded-full flex items-center justify-center" :class="{'text-primary border-87':label===item.down}">{{label}}</view>
              <view class="flex-1 pl-24" :class="{'text-primary':label===item.down}">{{value}}</view>
            </view>
          </view>
        </view>
      </swiper-item>
    </swiper>
    <view class="box-shadows flex items-center justify-between px-32">
      <view class="flex items-center font-28 py-32" @click="showDialog=true">
        <image src="/static/images/q_answer_sheet_number.png" class="icon-36 mr-12"/>
        {{currentIndex+1}}/{{list.length}}
      </view>
      <view class="flex items-center font-28 py-32 text-primary" @click="submit">
        <image src="/static/images/white-icon.png" class="icon-36 mr-12"/>
        交卷
      </view>
    </view>
    <u-popup :show="showDialog" @close="showDialog=false" :round="10">
      <view class="p-32">
        <view class="flex items-center justify-between ">
          <view class="flex items-center font-28 " @click="showDialog=false">
            <image src="/static/images/q_answer_sheet_number.png" class="icon-36 mr-12"/>
            {{currentIndex+1}}/{{list.length}}
          </view>
          <view class="flex items-center font-28 " @click="submit">
            <image src="/static/images/white-icon.png" class="icon-36 mr-12"/>
            交卷
          </view>
        </view>
      </view>
      <scroll-view class="min-h-700 max-h-900" scroll-y>
        <view class="grid-box6 px-32 pb-32">
          <view class="w-100 h-100 border border-dd rounded-full flex items-center justify-center" @click="currentIndex=index;showDialog=false" v-for="(item, index) in list" :key="index"
                :class="{
              'border-72dd70 color-72dd70 bg-daf6da':item.down,
              'border-87 text-primary':index===currentIndex,
           }"
          >
            <view class="">{{index+1}}</view>
          </view>
        </view>
      </scroll-view>
    </u-popup>
    <u-popup :show="useStore.isPrompt" @close="useStore.isPrompt=false" mode="center" bgColor="transparent" overlayOpacity="0.8">
      <view class="text-ff">
        <view class='flex items-center'>
          <image src='/static/images/left_slide.png' class="w-84 h-76 zuo"></image>
          <view class="mx-24"> 手指左右滑动切题 </view>
          <image src='/static/images/right_slide.png' class="w-84 h-76 you"></image>
        </view>
        <view class="h-200"></view>
        <view class='border border-ff w-full px-24 py-24 text-center rounded-48' @click='useStore.isPrompt=false'>记住了 开始考试</view>
        <view class="h-200"></view>
      </view>
    </u-popup>
  </view>
</template>
<script setup>
import {ref} from 'vue'
import {onLoad} from "@dcloudio/uni-app"
import {subject} from '@/api'
import useUserStore from '@/store/user.js'
import useExam from '@/common/useExam.js'
import dayjs from "dayjs";
import UPopup from "../../../uni_modules/uview-plus/components/u-popup/u-popup.vue";

const useStore = useUserStore()
const {
  categoryId,
  count,
  currentIndex,
  list,
  questionType,
  showDialog,
  ContentRow,
} = useExam();
const time = ref(0)//倒计时
const useTime = ref({}) // 答题时间
onLoad( async (options) => {
  console.log(options)
  if(useStore.Exam&&useStore.Exam.id){
    categoryId.value=useStore.Exam.id
    currentIndex.value=useStore.Exam.currentIndex
    list.value=useStore.Exam.list
    const startTime = dayjs(useStore.Exam.startTime).format('YYYY-MM-DD HH:mm:ss')
    const endTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
    const useTime0  = useStore.Exam.time/1000 //转换为秒
    const useTime1 = dayjs(endTime).diff(startTime,'seconds')
    console.log('startTime',startTime)
    console.log('useTime0',useTime0)
    console.log('useTime1',useTime1)
    if(useTime0>useTime1){
      time.value = (useTime0-useTime1)*1000 // 单位：毫秒
    }else {
      time.value = 2  * 1000 // 单位：毫秒
    }
  }

  if (options && options.mnksExamMaxTime) {
    time.value = options.mnksExamMaxTime*60 * 1000 // 单位：毫秒
    // time.value = 2  * 1000 // 单位：毫秒
  }
  if (options && options.categoryId) {
    categoryId.value = options.categoryId
    await getQuestions()
  }
})
// 更改swiper当前项的回调
function onSwiperChange(e) {
  currentIndex.value = e.detail.current
}
// 单选题选项选择的回调
function onRadioChange(label) {
  list.value[currentIndex.value].down = label
  useStore.Exam = {
    currentIndex: currentIndex.value,
    list: list.value,
    time: time.value,
    id: categoryId.value,
    startTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  }
  //判断是否是最后一题
  if(currentIndex.value >= list.value.length-1) return uni.showModal({
    title: '提示',
    content: '已是最后一题，是否提交试卷？',
    success: (res) => {
      if (res.confirm) {
        console.log('提交试卷')
        submit(2)
      } else if (res.cancel) {
        console.log('取消提交')
      }
    }
  })
   currentIndex.value++
}
//获取当前题目
const getQuestions = async () => {
  const res = await  subject.getSubjectQuestion({categoryId:categoryId.value })
  console.log(res)
  if (res.code === 0) {
    count.value = res.count || 0
    //顺序练习
    let arr = res.data || []
    list.value = arr.map(item => {
      return convertToObj2Format(item)
    })
    console.log('题目列表1', arr)
    list.value.forEach(item => {
      item.down = ''
    })
    console.log('题目列表', list.value)
  }
}
// 交卷`
const submitApi = async () => {
  //毫秒转换为秒
  const time1 = time.value / 1000
  const time2 = useTime.value.days * 24 * 60 * 60 + useTime.value.hours * 60 * 60 + useTime.value.minutes * 60 + useTime.value.seconds
  const time3 = time1 - time2
  const res = await subject.getSubjectSubmit({
    categoryId: categoryId.value,
    useTime:time3? time3 : time1,
    uid: useStore.uid,
    subjectReqVOList: list.value.map(item => {
      return {
        subjectId: item.subjectId,
        subjectType: item.subjectType,
        answer: item.down
      }
    })
  })
  console.log(res)
  if (res.code === 0) {
    useStore.Exam = null
    ContentRow.value = res.data || {}
    uni.redirectTo({
      url: '/pages/index/SimulatedExam/score?params='+JSON.stringify(res.data)
    })
  }
}
const submit = async (type) => {
  if(type===2){
    await submitApi()
  }else{
    const index = list.value.findIndex(item => !item.down)
    uni.showModal({
      title: '提示',
      content: index === -1 ? '是否提交试卷？':'还有未做的题目，是否提交试卷？',
      success: (res) => {
        if (res.confirm) {
          console.log('提交试卷')
          submitApi()
        } else if (res.cancel) {
          console.log('取消提交')
        }
      }
    })
  }

}
// 倒计时改变的回调
function onCountDownChange(e) {
  useTime.value = e
  // console.log('倒计时改变的回调',useTime.value)
  if(e.days===0 && e.hours===0 && e.minutes===0 && e.seconds===0){
    uni.showModal({
      title: '提示',
      content: '时间到，请提交试卷！',
      showCancel: false,
      success: (res) => {
        if (res.confirm) {
          console.log('提交试卷')
          submit(2)
        }
      }
    })
  }
}
// 定义一个函数来转换对象格式
function convertToObj2Format(obj) {
  const options = {}
  let choiceKey
  for (let i = 65; i <= 74; i++) { // ASCII码 A(65) 到 J(74)
    choiceKey = `choice${String.fromCharCode(i)}`
    if (obj[choiceKey]) {
      options[String.fromCharCode(i)] = obj[choiceKey]
    }
  }
  return {
    answerExplain: obj.answerExplain,
    categoryId: obj.categoryId,
    options: options,
    content: obj.content,
    difficultyLevel: obj.difficultyLevel,
    score: obj.score,
    standardAnswer: obj.standardAnswer,
    status: obj.status,
    subjectId: obj.subjectId,
    subjectType: obj.subjectType,
  }
}
</script>
<style scoped lang="scss">
.top10{
  top: -6rpx;
}
/* 定义向左下旋转的动画 */
@keyframes rotateToLeftDown {
  0% {
    transform: translateX(0) rotate(20deg); /* 初始位置：不移动，不旋转 */
  }
  100% {
    transform: rotate(-45deg); /* 向左移动并顺时针旋转 45 度 */
  }
}

/* 向左下旋转的图片 */
.zuo {
  animation: rotateToLeftDown 2s infinite ease-in-out;
}

</style>